<template>
  <div class="register-container">
    <h2>注册页面</h2>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="新账号" prop="newUsername">
        <el-input v-model="form.newUsername" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" autocomplete="off" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { registerApi } from '../utils/api.js';

export default {
  setup() {
    const router = useRouter();
    const form = reactive({
      newUsername: '',
      newPassword: ''
    });

    const rules = reactive({
      newUsername: [
        { required: true, message: '请输入新账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度为3-20个字符', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
      ]
    });

        const handleRegister = async () => {
            try {
                await registerApi(form.newUsername, form.newPassword); // 直接调用，不存储 response
                ElMessage.success('注册成功，请登录');
                router.push('/');
            } catch (error) {
                ElMessage.error(error.message || '注册失败，请重试');
            }
        };

    const goBack = () => {
      router.push('/');
    };

    return {
      form,
      rules,
      handleRegister,
      goBack
    };
  }
};
</script>

<style scoped>
.register-container {
  width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>